package cn.abellflower.flowerhomehandler.home.comm;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author gbzdyf@126.com
 * @Date 2020/10/23 10:03 上午
 */
@Slf4j
@Component
public class BeanHelper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanHelper.applicationContext = applicationContext;
    }

    /**
     * 获取上下文对象
     *
     * @return applicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 根据name获取bean
     *
     * @param name
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name) {
        if (checkApplicationContext()) {
            return (T) getApplicationContext().getBean(name);
        } else {
            throw new RuntimeException();
        }
    }

    /**
     * 判断上下文对象是否为空
     *
     * @return
     */
    public static boolean checkApplicationContext() {
        boolean flag = getApplicationContext() != null;
        if (!flag) {
            log.error("applicationContext未注入,实现ApplicationContextAware的类必须被spring管理");
        }
        return flag;
    }

    /**
     * 根据name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        if (checkApplicationContext()) {
            return getApplicationContext().getBean(name, clazz);
        } else {
            return null;
        }
    }

    /**
     * 根据Clazz返回指定的Bean
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        if (checkApplicationContext()) {
            return getApplicationContext().getBean(clazz);
        } else {
            return null;
        }
    }
}
